var http = require('http');
var fs = require('fs');
var util = require('util');
var querystring = require('querystring');
var setName = '留言板';
var port = 80;
var ip = '127.0.0.1';
var server = http.createServer(function (request, response) {
	response.statusCode = 200;
	response.setHeader('Content-Type', 'text/html');
	response.setHeader('server','private server');

	var data = '404';
	var url = require('url'); 
	var p = url.parse(request.url,true)
	/*console.log(p)*/
	if (p.pathname == '/index.html') {
		try{
			data = fs.readFileSync('.'+request.url,'utf-8').replace(/%title/g,setName);
			item = fs.readFileSync('data.json','utf8');
			item = JSON.parse(item);
			var s = '';
			for (var i = 0; i < item.length; i++) {
				s += '<div class="item">';
				s += '<h6>'+item[i].author+'<span>'+item[i].time+'</span></h6>';
				s += '<p>'+item[i].message+'<a href="/delmessage?id='+i+'">删除</a></p>';
				s += '</div>';
			}
			data = data.replace(/%main/g,s);
		}catch(e){
			
		}
		response.write(data);
		response.end();		
	}else if (p.pathname == '/form.html') {
		data = fs.readFileSync('.'+request.url,'utf-8')
		response.write(data);
		response.end();	
	}else if (p.pathname == '/addmessage') {
		/*author = p.query.author;
		message = p.query.message;
		item = JSON.parse(fs.readFileSync('data.json','utf8'));
		item.push({
			author:author,
			message:message,
			time:new Date()
		})
		item = JSON.stringify(item);
		fs.writeFileSync('data.json',item)
		data = '提交成功'
		response.writeHead(302,{'Location':'/index.html'});*/

		var post = '';     
	    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
	    request.on('data', function(data){    
	        post += data;
	    });	 
	    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
	    request.on('end', function(data){ 
	    	console.log(post)   
	        post = querystring.parse(post);
	        item = JSON.parse(fs.readFileSync('data.json','utf8'));
	        item.push({
				author:post.author,
				message:post.message,
				time:new Date()
			})
			fs.writeFileSync('data.json',JSON.stringify(item))
			response.writeHead(302,{'Location':'/index.html'});
			response.end();		
    	});
    	
	}else if (p.pathname == '/delmessage') {
		id = p.query.id
		item = JSON.parse(fs.readFileSync('data.json','utf8'));
		item.splice(id,1)
		item = JSON.stringify(item);
		fs.writeFileSync('data.json',item)
		data = '提交成功'
		response.writeHead(302,{'Location':'/index.html'});
		response.write(data);
		response.end();		
	}
	/*data = util.format(data,setName,setName)*/
/*	console.log(data)*/
});
server.listen(port)
console.log('Server running at http://%s:%s/',ip,port);